package com.itheima.service.impl;

import com.github.wxpay.sdk.WXPayUtil;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.MemberDao;
import com.itheima.dao.OrderDao;
import com.itheima.dao.OrderSettingDao;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.pojo.Order;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderService;
import com.itheima.service.OrderSettingService;
import com.itheima.util.HttpClient;
import com.itheima.utils.DateUtils;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;



import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/*
* 体检预约服务
* */
@Service
@Transactional
public class OrderServiceImpl implements OrderService {
    @Autowired
     private OrderSettingDao orderSettingDao;
    @Autowired
    private MemberDao memberDao;
    @Autowired
    private OrderDao orderDao;
    //保存预约信息
    @Override
    public Result order(Map map) throws Exception {
        //1.检查用户所选择的预约日期是否已经提前进行了预约设置,如果没有则不能添加预约
        String orderDate = (String) map.get("orderDate");//预约日期
        //根据日期去查询是否有预约数据
        OrderSetting orderSetting= orderSettingDao.findByOrderDate(DateUtils.parseString2Date(orderDate));
        if (orderSetting==null) {
            //当天没有预约任务
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }
        //2.检查用户所选的预约日期是否已经约满了,如果约满则无法预约
        int number = orderSetting.getNumber();
        int reservations = orderSetting.getReservations();
        if(reservations >= number){
            //已经约满，无法预约
            return new Result(false,MessageConstant.ORDER_FULL);
        }
        //3.检查用户是否重复预约
        String telephone = (String) map.get("telephone");//获取用户页面输入的手机号
        Member member = memberDao.findByTelephone(telephone);
        if (member!=null) {
            //判断是否在重复预约
            Integer memberId = member.getId();//会员id
            Date order_Date = DateUtils.parseString2Date(orderDate);//预约日期
            String setmealId = (String) map.get("setmealId");//套餐ID
            Order order = new Order(memberId, order_Date, Integer.parseInt(setmealId));
            //根据order中封装的条件进行查询
            List<Order> list = orderDao.findByCondition(order);
            if(list != null && list.size() > 0){
                //说明用户在重复预约，无法完成再次预约
                return new Result(false,MessageConstant.HAS_ORDERED);
            }

        }else{
            //4、检查当前用户是否为会员，如果是会员则直接完成预约，如果不是会员则自动完成注册并进行预约
            member = new Member();
            member.setName((String) map.get("name"));
            member.setPhoneNumber(telephone);
            member.setIdCard((String) map.get("idCard"));
            member.setSex((String) map.get("sex"));
            member.setRegTime(new Date());
            memberDao.add(member);//自动完成会员注册

        }
        //可以预约,添加预约信息,并且更新预约人数
        Order order = new Order();
        order.setMemberId(member.getId());//设置会员ID
        order.setOrderDate(DateUtils.parseString2Date(orderDate));//预约日期
        order.setOrderType((String) map.get("orderType"));//预约类型
        order.setOrderStatus(Order.ORDERSTATUS_NO);//到诊状态
        order.setSetmealId(Integer.parseInt((String) map.get("setmealId")));//套餐ID
        orderDao.add(order);//添加后就会有id

        //拿到当前时间的预约人数信息(当前加一)
        orderSetting.setReservations(orderSetting.getReservations() + 1);
        orderSettingDao.editReservationsByOrderDate(orderSetting);
        return new Result(true,MessageConstant.ORDER_SUCCESS,order.getId());
    }

    @Override
    public Map findById(Integer id) throws Exception {
        Map map = orderDao.findById4Detail(id);
        if(map != null){
            //处理日期格式
            Date orderDate = (Date) map.get("orderDate");
            map.put("orderDate",DateUtils.parseDate2String(orderDate));
        }
        return map;
    }
//生成微信支付二维码接口
    @Override
    public Map createNatvie(Integer orderId) {
        try{
            //假数据
            BigDecimal bigDecimal = new BigDecimal(0.0001);
            System.out.println("金钱"+bigDecimal.multiply(new BigDecimal("100")).longValue()+"");
            //查询订单内容
            //通过订单中套餐的id找到套餐信息
            //2. 使用map 设置生成二维码所需要的参数
            Map m =new HashMap();
            m.put("appid","wx74862e0dfcf69954");//appid 是公众号id或者是商户id(必填)
            m.put("mch_id","1558950191");//mch_id 微信支付分配的商户号(必填)
            m.put("nonce_str",WXPayUtil.generateNonceStr());//要求带上随机字符传(必填),这里使用微信sdk提供的
            m.put("body","套餐名"); //商品简单描述(必填)
            m.put("out_trade_no","1245994"); //商户系统内部订单号(必填)
            m.put("total_fee",bigDecimal.multiply(new BigDecimal("100")).longValue()+"");//金钱
            m.put("spbill_create_ip","127.0.0.1");//终端地址(必填)
            m.put("notify_url","http://guli.shop/api/order/weixinPay/weixinNotify\n");//异步接收微信支付结果通知的回调地址，通知url必须为外网可访问的url，不能携带参数。(必填)
            m.put("trade_type","NATIVE");//交易类型(native是扫码登录,必填)
             //注意发送给支付终端它要求传递参数用xml的格式,发送到微信支付提供的固定地址
            //3.发送httpclient 请求,传递参数
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            //设置xml格式的参数
            client.setXmlParam(WXPayUtil.generateSignedXml(m,"T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"));
            client.setHttps(true);
            //执行post请求发送
            client.post();
            //4.得到发送请求返回的结果
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            //最终返回数据的封装
            Map map=new HashMap();
            map.put("out_trade_no", "订单的id");
            map.put("result_code", resultMap.get("result_code"));  //返回二维码操作状态码
            map.put("code_url", resultMap.get("code_url"));//返回的二维码地址
            System.out.println("支付的二维码地址"+resultMap.get("code_url"));
            return map;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }

    }
}
